<template>
  <el-form ref="loginForm"
           :rules="loginRules"
           :model="loginForm"
           class="login-form"
           status-icon
           label-width="0">
    <el-form-item prop="email">
      <el-input v-model="loginForm.email"
                size="small"
                auto-complete="off"
                placeholder="请输入邮箱"
                @keyup.enter.native="handleLogin">
        <i slot="prefix"
           class="el-icon-s-promotion" />
      </el-input>
    </el-form-item>
    <el-form-item prop="code">
      <el-input v-model="loginForm.code"
                size="small"
                auto-complete="off"
                placeholder="请输入验证码"
                @keyup.enter.native="handleLogin">
        <i slot="prefix"
           class="el-icon-key"
           style="margin-top:6px;" />
        <template slot="append">
          <span :class="[{display:msgKey}]"
                class="msg-text"
                @click="handleSend">{{ msgText }}</span>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item>
      <el-button size="small"
                 type="primary"
                 class="login-submit"
                 @click.native.prevent="handleLogin">登录</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
const MSGINIT = "邮箱验证码",
  MSGSCUCCESS = "${time}秒后重发",
  MSGTIME = 60;
import { validateEmail } from "@/util/validate";
import { mapGetters } from "vuex";
import { sendCode } from '@/api/common/code'
export default {
  name: "EmailLogin",
  data () {
    return {
      msgText: MSGINIT,
      msgTime: MSGTIME,
      msgKey: false,
      loginForm: {
        email: "",
        code: "",
      },
      loginRules: {
        email: [{
          required: true, trigger: "blur", validator: (rule, value, callback) => {
            if (validateEmail(value)) {
              callback();
            } else {
              callback(new Error("邮箱格式有误"));
            }
          }
        }],
        code: [{
          required: true, trigger: "blur", validator: (rule, value, callback) => {
            if (value.length != 6) {
              callback(new Error("请输入6位数的验证码"));
            } else {
              callback();
            }
          }
        }],
      },
    };
  },
  computed: {
    ...mapGetters(["tagWel"]),
  },
  methods: {
    handleSend () {
      // 判断是否可以发送（时间限制）
      if (this.msgKey) return;
      // 发送验证码
      this.$refs.loginForm.validateField("email", (errorMessage) => {
        if (!errorMessage) {
          sendCode({
            scenes: 'login',
            principal: this.loginForm.email,
            handlerType: 'email'
          }).then((response) => {
            this.$message.success(response.data.message);
            this.timeCacl();
          });
        }
      });
    },
    handleLogin () {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.$store.dispatch("LoginByEmail", this.loginForm).then(() => {
            this.$router.push({ path: this.tagWel.value });
          });
        }
      });
    },
    timeCacl () {
      // 计时避免重复发送
      this.msgText = MSGSCUCCESS.replace("${time}", this.msgTime);
      this.msgKey = true;
      const time = setInterval(() => {
        this.msgTime--;
        this.msgText = MSGSCUCCESS.replace("${time}", this.msgTime);
        if (this.msgTime === 0) {
          this.msgTime = MSGTIME;
          this.msgText = MSGINIT;
          this.msgKey = false;
          clearInterval(time);
        }
      }, 1000);
    },
  },
};
</script>

<style>
.msg-text {
  display: block;
  width: 60px;
  font-size: 12px;
  text-align: center;
  cursor: pointer;
}
.msg-text.display {
  color: #ccc;
}
</style>
